package cn.lopr.im.api.service.impl;

import cn.lopr.im.api.annotation.DataSource;
import cn.lopr.im.api.bean.*;
import cn.lopr.im.api.configuration.datasources.DynamicDataSourceEnum;
import cn.lopr.im.api.dao.FriendMapper;
import cn.lopr.im.api.dao.MessageMapper;
import cn.lopr.im.api.dao.UserMapper;
import cn.lopr.im.api.service.ICommunityDBService;
import cn.lopr.im.api.service.IUserService;
import cn.lopr.im.api.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Stream;

/**
 * @author shuangyang7
 * @date 2020/12/28 15:30
 */
@Service(value = "userService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FriendMapper friendMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private ICommunityDBService communityDBService;

    @Override
    @DataSource(DynamicDataSourceEnum.MASTER)
    public User getUserById(Integer id) {
        return userMapper.selectByRecord(new User().setId(id)).setPassword(null);
    }

    @Override
    public User login(String phone, String password) {
        User user = userMapper.selectByRecord(new User().setPhone(phone));

        if (user != null) {
            if (!user.getPassword().equals(password)) {
                user = null;
            }
        }

        return user;
    }

    @Override
    public User autoLogin(String phone) {

        return userMapper.selectByRecord(new User().setPhone(phone));
    }

    @Override
    public List<User> getFriend(User user) {
        return userMapper.selectByFriend(new Friend().setSponsor(user.getPhone()));
    }

    @Override
    public List<User> getFriendByPhones(String[] phones) {
        return userMapper.selectByPhones(Arrays.asList(phones));
    }

    @Override
    @DataSource(DynamicDataSourceEnum.SLAVE)
    public User getUser() {
        return userMapper.selectByPrimaryKey(1);
    }

    @Override
    public User reg(String phone, String password, String name) {

        User tmp = userMapper.selectByRecord(new User().setPhone(phone));

        if (tmp != null) {
            return null;
        }

        User user = new User().setNickname(name).setPassword(password).setPhone(phone);
        int insert = userMapper.insert(user);
        if (insert == 0) {
            return null;
        }
        return userMapper.selectByRecord(new User().setPhone(phone));
    }

    @Override
    public boolean regBefore(User user) {
        int i = userMapper.updateByRecord(user);

        return i != 0;
    }

    @Override
    public boolean updateUser(User user) {
        int i = userMapper.updateByRecord(user);

        return i != 0;
    }

    @Override
    public List<UserVo> searchFriend(String myPhone, String content) {
        List<User> friend = getFriend(new User().setPhone(myPhone));
        List<User> users = userMapper.selectByPhone(content);
        List<User> result = new ArrayList<>();

        List<Message> messages = messageMapper.selectByRecord(new Message()
                .setType(Message.MessageType.SEND_ADD.getCode() + "")
                .setFromUser(myPhone));

        for (User user : users) {
            if (!user.getPhone().equals(myPhone) && !friend.contains(user)) {
                result.add(user);
            }
        }
        List<UserVo> userVos = new ArrayList<>();
        for (User user : result) {
            Stream<Message> messageStream = messages.stream().filter(message -> message.getToUser().equals(user.getPhone()));
            UserVo userVo = new UserVo(user);
            if (messageStream.count() != 0) {
                userVo.setApply(true);
            }
            userVo.setPassword(null);
            userVos.add(userVo);
        }

        return userVos;
    }

    @Override
    public boolean addFriend(String myPhone, String phone) {
        friendMapper.insertSelective(new Friend().setRecipient(phone).setSponsor(myPhone));
        friendMapper.insertSelective(new Friend().setRecipient(myPhone).setSponsor(phone));
        //messageMapper.updateReadMessageByType(myPhone, phone, Message.MessageType.SEND_ADD.getCode() + "");

        return true;
    }

    @Override
    @DataSource(DynamicDataSourceEnum.COMMUNITY)
    public Map<String, Integer> getLikeMeLikeYouVisitPublish(Integer userId) {

        int publishNum;
        int likeYouNum;
        int likeMeNum = 0;
        int visitNum = 0;

        Article article = new Article();
        article.setPublishUserId(userId);
        article.setIsDelete(false);
        List<Article> articles = communityDBService.selectArticleByRecord(article);

        publishNum = articles.size();

        // 多少人给我点赞
        for (Article articleItem : articles) {
            likeMeNum += communityDBService.selectArticleOptionByRecord(new ArticleOption()
                    .setArticleId(articleItem.getId()).setOptionType(Option.OptionType.LIKE.getCode()).setIsDelete(false)).size();
            // 我的文章浏览量
            visitNum += communityDBService.selectArticleOptionByRecord(new ArticleOption()
                    .setArticleId(articleItem.getId()).setOptionType(Option.OptionType.VISIT.getCode()).setIsDelete(false)).size();
        }

        // 我给多少人点赞
        List<ArticleOption> articleOptionsByLike = communityDBService.selectArticleOptionByRecord(new ArticleOption()
                .setUserId(userId).setIsDelete(false).setOptionType(Option.OptionType.LIKE.getCode()));
        likeYouNum = articleOptionsByLike.size();

        int finalLikeMeNum = likeMeNum;
        int finalVisitNum = visitNum;

        return new HashMap<String, Integer>() {{
            put("publishNum", publishNum);
            put("likeYouNum", likeYouNum);
            put("likeMeNum", finalLikeMeNum);
            put("visitNum", finalVisitNum);
        }};
    }

}
